<?php
/*
 * @Author: your name
 * @Date: 2020-06-29 09:28:29
 * @LastEditTime: 2020-09-30 17:49:01
 * @LastEditors: 天羽落星辰
 * @Description: In User Settings Edit
 * @FilePath: \WWW\frx\application\api\controller\Index.php
 */

namespace app\api\controller;

use think\Db;
use app\admin\model\Order;
use app\common\model\User;
use app\common\controller\Api;
use app\admin\model\QianbaoSysetmLog;
use app\admin\model\Contract as ModelContract;

/**
 * 合约接口
 */
class Contract extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * 合约列表
     */
    public static function index()
    {

        $bls_usdt = config('site.bls_usdt');
        $list = ModelContract::where(['status' => 1])->order('id desc')->select();
        if ($list) {
            foreach ($list as $k => &$v) {
                $v['total_revenue'] = $v['total_revenue'] * 1;
                $v['money'] = $v['money'] * 1;
                $v['money'] .= 'U (赠送'.($v['money'] * $bls_usdt).'BLS)';
                $v->hidden(['description', 'status', 'updatetime', 'createtime']);
            }
        }

        return ($list);
        // $this->success('', $list);
    }

    /**
     * 提交合约
     * @param string $id  合约ID
     * @param string $password  支付密码
     * @param string $money  支付金额
     */
    public function add()
    {   
        
        $id = $this->request->request("id");
        $password = $this->request->request("password");
        // $money = $this->request->request("money");
        $user = $this->auth->getuser();
        $bls_usdt = config('site.bls_usdt');

        
        
        $row = ModelContract::get($id);
        $moneymin = config('site.touzhi_moeny_min');
        
        if (!$row)
            $this->error(__('No Results were found'));
            
            if (md5($password) != $user['secpwd']) {
                $this->error('密码错误');
            }
            $order_count = db('order')->where('uid',$user['id'])->where('zt',1)->where('contract_id',$row['id'])->count();
            
            if($order_count >= $row['nums'])
            $this->error(__('对不起，该合约购买次数达到上限'));

            if ($row['money'] > $this->auth->usdt) {
                $this->error('余额不足');
        }
        
        // 直推奖
        // $zhitui = zhitui($user->toArray(),$money);
        
        // 启动事务
        Db::startTrans();
        try {
            db('user')->where('id', $this->auth->id)->lock(true)->count();
            $a1 = db('user')->where('id', $this->auth->id)->dec('usdt', $row['money'])->inc('bls_frozen', ($row['money'] * $bls_usdt))->inc('order_sum', $row['money'])->update();
            $a2 = db('order')->insert([
                'uid' => $user['id'],
                'uname' => $user['username'],
                'danhao' => orderSn(),
                'price' => $row['money'],
                'shouyi' => $row['total_revenue'],
                'zhouqi' => $row['day'],
                'contract_id' => $row['id'],
                'bls' => $row['money'] * $bls_usdt,
                'overtime' => strtotime("+" . $row['day'] . " day"),
                'zt' => 1,
                'createtime' => time(),
            ]);
            
            $a3 = db('qianbao_sysetm_log')->insert([
                'uid' => $user['id'],
                'uname' => $user['username'],
                'bizhong' => 'usdt',
                'money' => -$row['money'],
                'before' => $user['usdt'],
                'after' => $user['usdt'] - $row['money'],
                'type' => 5,
                'zt' => 1,
                'memo' => '参与合约扣除'.$row['money'].'USDT',
                'createtime' => time(),
            ]);


            // if($zhitui){
            //     $qianbaosysetmlog = new QianbaoSysetmLog;
            //     $users = new User;
                
            //     if(!$qianbaosysetmlog->save($zhitui['qian_log'], false)){
            //         throw new \Exception("接单失败",1);
            //     }

            //     if(!$users->isUpdate()->save($zhitui['user'])){
            //         throw new \Exception("接单失败",2);
            //     }
            // }

            if (!$a1 && !$a2 && !$a3) {
                throw new \Exception("接单失败");
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $th) {
            // 回滚事务
            Db::rollback();
            $this->error(($th->getMessage()));
        }
        $this->success('接单成功');
    }

    /**
     * 执行中的合约理财列表
     * @param string $limit  页数列表显示条数
     * @param string $paging 页数
     */
    public function executing_list()
    {
        $limit = intval($this->request->request('limit'));
        $paging = intval($this->request->request('paging'));
        $score_to_usdt = config('site.score_to_usdt');
        $bls_usdt = config('site.bls_usdt');
        $limit = $limit ? $limit : 10;
        $paging = $paging ? 10 * $paging : 0;

        $data = db('order')->field('id,danhao, price, shouyi, createtime,overtime,current_profit,switch_token')->where('uid', $this->auth->id)
            ->where('zt', 1)
            ->limit($paging, $limit)
            ->order('id', 'desc')
            // ->fetchSql(true)
            ->select();

        if ($data) {
            foreach ($data as &$v) {
                $v['createtime'] = datetime($v['createtime']);
                $v['overtime'] = datetime($v['overtime']);
                $v['price'] = $v['price'] * $bls_usdt;
                $v['current_profit'] = $v['current_profit'] * 1;
                $v['shouyi'] = $v['shouyi'] * 1;
            }
        }
        $this->success('', $data);
    }

    /**
     * 历史的合约理财列表
     * @param string $limit  页数列表显示条数
     * @param string $paging 页数
     */
    public function history_list()
    {
        $limit = intval($this->request->request('limit'));
        $paging = intval($this->request->request('paging'));
        $bls_usdt = config('site.bls_usdt');
        $limit = $limit ? $limit : 10;
        $paging = $paging ? 10 * $paging : 0;

        $data = db('order')->field('id,danhao, price, shouyi,createtime,overtime,current_profit')->where('uid', $this->auth->id)
            ->where('zt', '<>', 1)
            ->limit($paging, $limit)
            ->order('id', 'desc')
            // ->fetchSql(true)
            ->select();

        if ($data) {
            foreach ($data as &$v) {
                $v['createtime'] = datetime($v['createtime']);
                $v['stoptime'] = datetime($v['overtime']);
                $v['price'] = $v['price'] * $bls_usdt;
                $v['current_profit'] = round($v['current_profit'],2);
            }
        }

        $this->success('', $data);
    }

    /**
     * 合约可设置自动转换其它代币（可相互转化）
     * @param int $id  订单ID
     */
    public function switch_token()
    {   
        $id = intval($this->request->request('id'));
        $row = Order::get($id);
        if (!$row)
            $this->error(__('No Results were found'));
        if($row['switch_token'] == 1){
            // $this->error('无需在转换，请刷新查看');
            $switch_token = 0;
        }else{
            $switch_token = 1;
        }

        if(!Order::update(['id' => $id, 'switch_token' => $switch_token])){
            $this->error('转换失败');
        }
        
        $this->success('转换成功');
    }

    // 领导奖
    private function reward($user,$row)
    {   
        return  reward($user->toArray(),$row->toArray());
    }
}
